<template>
  <pre><code class="scroll-wrapper code-wrapper" :class="lang" autodetect>{{content}}</code></pre>
</template>

<script>
if (hljs === undefined) {
  var hljs = window.hljs;
}
import {NoteScope} from "@js/constants.js";

export default {
  components: {},
  props: ["content", "lang"],
  mounted() {
    for (let block of this.$el.getElementsByClassName("code-wrapper")) {
      hljs.highlightBlock(block);
      this.addLineNum(block);
      window.Scrollbar.init(block, { alwaysShowTracks: true, damping: 0.6 });
      this.addSelection(block);
    }
  },
  methods: {
    addLineNum(block) {
      let html = block.innerHTML;
      let lines = html.split("\n");
      let lis = lines.map((l, i) => '<li class="code-line" linenum="' + (i+1) + '">' + l + '</li>');
      block.innerHTML = '<ol class="code-block">' + lis.join("") + '</ol>';
    },
    addSelection(block) {
      let lines = block.getElementsByClassName("code-line");
      for (let line of lines) {
        line.onclick = () => {
          let linenum = Number(line.getAttribute("linenum"));
          let sel = {
              scope: NoteScope.Line,
              line: Number(linenum),
              content: line.textContent,
          }; 
         this.$emit("select", sel);
        }
      }
    }
  },
};
</script>

<style lang="stylus">
.code-wrapper
  height 84vh
  margin-left 0
  padding-right 0

  &.hljs
    padding 0
    border 1px solid #eee
    width calc(100% - 0.15vw)

  .scroll-content
    font-family monospace
    font-size 14px
    width auto
    tab-size 2

    ol.code-block
      list-style-type decimal
      padding-left 3em
      width fit-content
    ol.code-block>li.code-line
      margin 0
      padding 5px
      list-style: decimal-leading-zero
      border-left 1px solid #eee
      background-color #fff

      &::marker
        color #aaa

      &:nth-of-type(even)
        background-color #fcfcfc

      &.mark::marker
        font-weight bold

      &.mark
        background-color #C6E2FF

      &:hover
        background-color #eee


.hljs
  width auto

</style>